﻿package
{
	import org.flixel.*;
	import org.flixel.plugin.photonstorm.FlxWeapon;
	import org.flixel.plugin.photonstorm.FlxCollision;
	
	
	public class Enemy2 extends NociveSprite
	{
		[Embed(source="data/enemy2.png")] private var ImgEnemy:Class;
		[Embed(source="data/golpe.mp3")] private var SoundHurt:Class;

		public var invencibility:int;
		public var damagebackup:Number;
		
		public function Enemy2(X:Number, Y:Number)
		{
			super(X, Y, damage);
			loadGraphic(ImgEnemy,true,true,41,34);
			maxVelocity.x = 100;			//walking speed
			acceleration.y = 400;			//gravity
			drag.x = maxVelocity.x*4;		//deceleration (sliding to a stop)
			
			//tweak the bounding box for better feel
			width = 27;
			height = 33;
			offset.x = 2;
			offset.y = 1;
			health = 5;
			damage = 1;
			solid = true;
			
			addAnimation("walk",[0,1,2,3,4],8,false);
			addAnimation("idle",[3]);
			
			damagebackup = damage;
			invencibility = 0;
			
			facing = RIGHT;
			
			(FlxG.state as Level1).add(this);
			(FlxG.state as Level1).damagersensible.add(this);
			
		}
		
		public function isNotTouchingfloor():Boolean
			{
				var isnttouch:Boolean;
				var deltaX:int;
				if(facing == LEFT)deltaX=0;
				if(facing == RIGHT)deltaX=width;
				if(((FlxG.state as Level1)._level.getTile((x+deltaX)/15,(y+height)/15) < 1)
				||((FlxG.state as Level1)._level.getTile((x+deltaX)/15,(y+height)/15) == 6)
				||((FlxG.state as Level1)._level.getTile((x+deltaX)/15,(y+height)/15) == 8))				 			                  isnttouch = true;
				else isnttouch = false; 
				return isnttouch;
			}
		
		
		
		override public function update():void
		{
		play("walk");	

		if(invencibility > 0)
				{
					invencibility--;
					velocity.x = 0;
					velocity.y = 0;
					if(invencibility == 0)visible = true;
					else if([1,5,9].indexOf(invencibility) != -1)visible = false;
					else if([3,7].indexOf(invencibility) != -1) visible = true;
					damage = 0;
				}
		else damage = damagebackup;
		
		if(isTouching(WALL) || isNotTouchingfloor())
			facing = (facing == LEFT ? RIGHT : LEFT);

			
		var distance:int;
		distance = (FlxG.state as Level1).player.x - this.x;
		
		if( distance <= 60 && distance > 1 )
		    facing = RIGHT;
		if( distance >= -60 && distance < -1 )
		    facing = LEFT;
			
		velocity.x = (facing == LEFT ? -80 : 80);
		
		if (distance <= 1 && distance >= -1){ 
			velocity.x = 0;
			facing = RIGHT
			play("idle");}
	    
		}
		
		

		
		
		override public function hurt(Damage:Number): void
		{
			if(Damage > 0)
			if(invencibility == 0){
				FlxG.play(SoundHurt);
				super.hurt(Damage);
				invencibility = 10;
				damagebackup = damage;
				if(velocity.x > 0)
				 x -= 3;
				if(velocity.x < 0)
				 x += 3;
				}
				 
		}
		
	}
}
